import json
import os
import hashlib
import time
from typing import Dict, Optional, Tuple


class UserSystem:
    def __init__(self, data_file: str = "users.json"):
        """
        初始化用户系统
        
        Args:
            data_file: 用户数据文件路径
        """
        self.data_file = data_file
        self.users = self._load_users()
        self.current_user = None
        
    def _load_users(self) -> Dict:
        """
        从JSON文件加载用户数据
        
        Returns:
            用户数据字典
        """
        if os.path.exists(self.data_file):
            try:
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except (json.JSONDecodeError, UnicodeDecodeError):
                print(f"警告：用户数据文件 {self.data_file} 损坏，创建新文件")
                return {"users": {}}
        else:
            return {"users": {}}
    
    def _save_users(self) -> None:
        """保存用户数据到JSON文件"""
        with open(self.data_file, 'w', encoding='utf-8') as f:
            json.dump(self.users, f, ensure_ascii=False, indent=2)
    
    def _hash_password(self, password: str) -> str:
        """
        使用SHA-256哈希密码
        
        Args:
            password: 原始密码
            
        Returns:
            密码哈希值
        """
        return hashlib.sha256(password.encode()).hexdigest()
    
    def register(self, username: str, password: str) -> Tuple[bool, str]:
        """
        注册新用户
        
        Args:
            username: 用户名
            password: 密码
            
        Returns:
            (成功状态, 消息)
        """
        # 检查用户名是否已存在
        if username in self.users["users"]:
            return False, "用户名已存在"
        
        # 检查用户名和密码是否有效
        if not username or len(username) < 3:
            return False, "用户名太短（至少3个字符）"
        
        if not password or len(password) < 6:
            return False, "密码太短（至少6个字符）"
        
        # 创建新用户
        self.users["users"][username] = {
            "password_hash": self._hash_password(password),
            "created_at": time.time(),
            "last_login": None,
            "login_count": 0,
            "preferences": {}
        }
        
        self._save_users()
        return True, "注册成功"
    
    def login(self, username: str, password: str) -> Tuple[bool, str]:
        """
        用户登录
        
        Args:
            username: 用户名
            password: 密码
            
        Returns:
            (成功状态, 消息)
        """
        if username not in self.users["users"]:
            return False, "用户名不存在"
        
        user_data = self.users["users"][username]
        if user_data["password_hash"] != self._hash_password(password):
            return False, "密码错误"
        
        # 更新登录信息
        user_data["last_login"] = time.time()
        user_data["login_count"] += 1
        self.current_user = username
        
        self._save_users()
        return True, "登录成功"
    
    def logout(self) -> None:
        """用户登出"""
        self.current_user = None
    
    def is_logged_in(self) -> bool:
        """检查是否已登录"""
        return self.current_user is not None
    
    def get_current_user(self) -> Optional[str]:
        """获取当前登录用户名"""
        return self.current_user
    
    def update_password(self, username: str, old_password: str, new_password: str) -> Tuple[bool, str]:
        """
        更新用户密码
        
        Args:
            username: 用户名
            old_password: 旧密码
            new_password: 新密码
            
        Returns:
            (成功状态, 消息)
        """
        if username not in self.users["users"]:
            return False, "用户名不存在"
        
        user_data = self.users["users"][username]
        if user_data["password_hash"] != self._hash_password(old_password):
            return False, "旧密码错误"
        
        if not new_password or len(new_password) < 6:
            return False, "新密码太短（至少6个字符）"
        
        user_data["password_hash"] = self._hash_password(new_password)
        self._save_users()
        
        return True, "密码更新成功"
    
    def save_user_preference(self, key: str, value) -> bool:
        """
        保存用户偏好设置
        
        Args:
            key: 设置键名
            value: 设置值
            
        Returns:
            是否成功
        """
        if not self.current_user:
            return False
        
        user_data = self.users["users"][self.current_user]
        user_data["preferences"][key] = value
        self._save_users()
        
        return True
    
    def get_user_preference(self, key: str, default=None):
        """
        获取用户偏好设置
        
        Args:
            key: 设置键名
            default: 默认值
            
        Returns:
            设置值或默认值
        """
        if not self.current_user:
            return default
        
        user_data = self.users["users"][self.current_user]
        return user_data["preferences"].get(key, default)
    
    def get_user_data(self, username: str = None) -> Optional[Dict]:
        """
        获取用户数据
        
        Args:
            username: 用户名，默认为当前用户
            
        Returns:
            用户数据字典
        """
        username = username or self.current_user
        if not username or username not in self.users["users"]:
            return None
        
        return self.users["users"][username] 